home *** CD-ROM | disk | FTP | other *** search
/ PD Collection CD 1 / PD Collection CD 1.iso / textual / gnudiff / C / Analyze next >
Text File  |  1991-09-16  |  26KB  |  894 lines

  1. /* Analyze file differences for GNU DIFF.
  2.    Copyright (C) 1988, 1989 Free Software Foundation, Inc.
  3.  
  4. This file is part of GNU DIFF.
  5.  
  6. GNU DIFF is free software; you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation; either version 1, or (at your option)
  9. any later version.
  10.  
  11. GNU DIFF is distributed in the hope that it will be useful,
  12. but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14. GNU General Public License for more details.
  15.  
  16. You should have received a copy of the GNU General Public License
  17. along with GNU DIFF; see the file COPYING.  If not, write to
  18. the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
  19.  
  20. /* The basic algorithm is described in: 
  21.    "An O(ND) Difference Algorithm and its Variations", Eugene Myers,
  22.    Algorithmica Vol. 1 No. 2, 1986, p 251.  */
  23.  
  24. #include "diff.h"
  25.  
  26. static int diag (int, int, int, int, int *);
  27. static void compareseq (int, int, int, int);
  28. static void shift_boundaries (struct file_data *);
  29. static struct change *add_change (int, int, int, int, struct change *);
  30. static struct change *build_reverse_script (struct file_data *);
  31. static struct change *build_script (struct file_data *);
  32.  
  33. extern int no_discards;
  34.  
  35. static int *xvec, *yvec;    /* Vectors being compared. */
  36. static int *fdiag;        /* Vector, indexed by diagonal, containing
  37.                    the X coordinate of the point furthest
  38.                    along the given diagonal in the forward
  39.                    search of the edit matrix. */
  40. static int *bdiag;        /* Vector, indexed by diagonal, containing
  41.                    the X coordinate of the point furthest
  42.                    along the given diagonal in the backward
  43.                    search of the edit matrix. */
  44.  
  45. /* Find the midpoint of the shortest edit script for a specified
  46.    portion of the two files.
  47.  
  48.    We scan from the beginnings of the files, and simultaneously from the ends,
  49.    doing a breadth-first search through the space of edit-sequence.
  50.    When the two searches meet, we have found the midpoint of the shortest
  51.    edit sequence.
  52.  
  53.    The value returned is the number of the diagonal on which the midpoint lies.
  54.    The diagonal number equals the number of inserted lines minus the number
  55.    of deleted lines (counting only lines before the midpoint).
  56.    The edit cost is stored into *COST; this is the total number of
  57.    lines inserted or deleted (counting only lines before the midpoint).
  58.  
  59.    This function assumes that the first lines of the specified portions
  60.    of the two files do not match, and likewise that the last lines do not
  61.    match.  The caller must trim matching lines from the beginning and end
  62.    of the portions it is going to specify.
  63.  
  64.    Note that if we return the "wrong" diagonal value, or if
  65.    the value of bdiag at that diagonal is "wrong",
  66.    the worst this can do is cause suboptimal diff output.
  67.    It cannot cause incorrect diff output.  */
  68.  
  69. static int diag (int xoff, int xlim, int yoff, int ylim, int *cost)
  70. {
  71.   int *const fd = fdiag;    /* Give the compiler a chance. */
  72.   int *const bd = bdiag;    /* Additional help for the compiler. */
  73.   int *const xv = xvec;        /* Still more help for the compiler. */
  74.   int *const yv = yvec;        /* And more and more . . . */
  75.   const int dmin = xoff - ylim;    /* Minimum valid diagonal. */
  76.   const int dmax = xlim - yoff;    /* Maximum valid diagonal. */
  77.   const int fmid = xoff - yoff;    /* Center diagonal of top-down search. */
  78.   const int bmid = xlim - ylim;    /* Center diagonal of bottom-up search. */
  79.   int fmin = fmid, fmax = fmid;    /* Limits of top-down search. */
  80.   int bmin = bmid, bmax = bmid;    /* Limits of bottom-up search. */
  81.   int c;            /* Cost. */
  82.   int odd = fmid - bmid & 1;    /* True if southeast corner is on an odd
  83.                    diagonal with respect to the northwest. */
  84.  
  85.   fd[fmid] = xoff;
  86.   bd[bmid] = xlim;
  87.  
  88.   for (c = 1;; ++c)
  89.     {
  90.       int d;            /* Active diagonal. */
  91.       int big_snake = 0;
  92.  
  93.       /* Extend the top-down search by an edit step in each diagonal. */
  94.       fmin > dmin ? fd[--fmin - 1] = -1 : ++fmin;
  95.       fmax < dmax ? fd[++fmax + 1] = -1 : --fmax;
  96.       for (d = fmax; d >= fmin; d -= 2)
  97.     {
  98.       int x, y, oldx, tlo = fd[d - 1], thi = fd[d + 1];
  99.  
  100.       if (tlo >= thi)
  101.         x = tlo + 1;
  102.       else
  103.         x = thi;
  104.       oldx = x;
  105.       y = x - d;
  106.       while (x < xlim && y < ylim && xv[x] == yv[y])
  107.         ++x, ++y;
  108.       if (x - oldx > 20)
  109.         big_snake = 1;
  110.       fd[d] = x;
  111.       if (odd && bmin <= d && d <= bmax && bd[d] <= fd[d])
  112.         {
  113.           *cost = 2 * c - 1;
  114.           return d;
  115.         }
  116.     }
  117.  
  118.       /* Similar extend the bottom-up search. */
  119.       bmin > dmin ? bd[--bmin - 1] = INT_MAX : ++bmin;
  120.       bmax < dmax ? bd[++bmax + 1] = INT_MAX : --bmax;
  121.       for (d = bmax; d >= bmin; d -= 2)
  122.     {
  123.       int x, y, oldx, tlo = bd[d - 1], thi = bd[d + 1];
  124.  
  125.       if (tlo < thi)
  126.         x = tlo;
  127.       else
  128.         x = thi - 1;
  129.       oldx = x;
  130.       y = x - d;
  131.       while (x > xoff && y > yoff && xv[x - 1] == yv[y - 1])
  132.         --x, --y;
  133.       if (oldx - x > 20)
  134.         big_snake = 1;
  135.       bd[d] = x;
  136.       if (!odd && fmin <= d && d <= fmax && bd[d] <= fd[d])
  137.         {
  138.           *cost = 2 * c;
  139.           return d;
  140.         }
  141.     }
  142.  
  143.       /* Heuristic: check occasionally for a diagonal that has made
  144.      lots of progress compared with the edit distance.
  145.      If we have any such, find the one that has made the most
  146.      progress and return it as if it had succeeded.
  147.  
  148.      With this heuristic, for files with a constant small density
  149.      of changes, the algorithm is linear in the file size.  */
  150.  
  151.       if (c > 200 && big_snake && heuristic)
  152.     {
  153.       int best;
  154.       int bestpos;
  155.  
  156.       best = 0;
  157.       for (d = fmax; d >= fmin; d -= 2)
  158.         {
  159.           int dd = d - fmid;
  160.           if ((fd[d] - xoff)*2 - dd > 12 * (c + (dd > 0 ? dd : -dd)))
  161.         {
  162.           if (fd[d] * 2 - dd > best
  163.               && fd[d] - xoff > 20
  164.               && fd[d] - d - yoff > 20)
  165.             {
  166.               int k;
  167.               int x = fd[d];
  168.  
  169.               /* We have a good enough best diagonal;
  170.              now insist that it end with a significant snake.  */
  171.               for (k = 1; k <= 20; k++)
  172.             if (xvec[x - k] != yvec[x - d - k])
  173.               break;
  174.  
  175.               if (k == 21)
  176.             {
  177.               best = fd[d] * 2 - dd;
  178.               bestpos = d;
  179.             }
  180.             }
  181.         }
  182.         }
  183.       if (best > 0)
  184.         {
  185.           *cost = 2 * c - 1;
  186.           return bestpos;
  187.         }
  188.  
  189.       best = 0;
  190.       for (d = bmax; d >= bmin; d -= 2)
  191.         {
  192.           int dd = d - bmid;
  193.           if ((xlim - bd[d])*2 + dd > 12 * (c + (dd > 0 ? dd : -dd)))
  194.         {
  195.           if ((xlim - bd[d]) * 2 + dd > best
  196.               && xlim - bd[d] > 20
  197.               && ylim - (bd[d] - d) > 20)
  198.             {
  199.               /* We have a good enough best diagonal;
  200.              now insist that it end with a significant snake.  */
  201.               int k;
  202.               int x = bd[d];
  203.  
  204.               for (k = 0; k < 20; k++)
  205.             if (xvec[x + k] != yvec[x - d + k])
  206.               break;
  207.               if (k == 20)
  208.             {
  209.               best = (xlim - bd[d]) * 2 + dd;
  210.               bestpos = d;
  211.             }
  212.             }
  213.         }
  214.         }
  215.       if (best > 0)
  216.         {
  217.           *cost = 2 * c - 1;
  218.           return bestpos;
  219.         }
  220.     }
  221.     }
  222. }
  223.  
  224. /* Compare in detail contiguous subsequences of the two files
  225.    which are known, as a whole, to match each other.
  226.  
  227.    The results are recorded in the vectors files[N].changed_flag, by
  228.    storing a 1 in the element for each line that is an insertion or deletion.
  229.  
  230.    The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
  231.  
  232.    Note that XLIM, YLIM are exclusive bounds.
  233.    All line numbers are origin-0 and discarded lines are not counted.  */
  234.  
  235. static void compareseq (int xoff, int xlim, int yoff, int ylim)
  236. {
  237.   /* Slide down the bottom initial diagonal. */
  238.   while (xoff < xlim && yoff < ylim && xvec[xoff] == yvec[yoff])
  239.     ++xoff, ++yoff;
  240.   /* Slide up the top initial diagonal. */
  241.   while (xlim > xoff && ylim > yoff && xvec[xlim - 1] == yvec[ylim - 1])
  242.     --xlim, --ylim;
  243.   
  244.   /* Handle simple cases. */
  245.   if (xoff == xlim)
  246.     while (yoff < ylim)
  247.       files[1].changed_flag[files[1].realindexes[yoff++]] = 1;
  248.   else if (yoff == ylim)
  249.     while (xoff < xlim)
  250.       files[0].changed_flag[files[0].realindexes[xoff++]] = 1;
  251.   else
  252.     {
  253.       int c, d, f, b;
  254.  
  255.       /* Find a point of correspondence in the middle of the files.  */
  256.  
  257.       d = diag (xoff, xlim, yoff, ylim, &c);
  258.       f = fdiag[d];
  259.       b = bdiag[d];
  260.  
  261.       if (c == 1)
  262.     {
  263.       /* This should be impossible, because it implies that
  264.          one of the two subsequences is empty,
  265.          and that case was handled above without calling `diag'.
  266.          Let's verify that this is true.  */
  267.       abort ();
  268. #if 0
  269.       /* The two subsequences differ by a single insert or delete;
  270.          record it and we are done.  */
  271.       if (d < xoff - yoff)
  272.         files[1].changed_flag[files[1].realindexes[b - d - 1]] = 1;
  273.       else
  274.         files[0].changed_flag[files[0].realindexes[b]] = 1;
  275. #endif
  276.     }
  277.       else
  278.     {
  279.       /* Use that point to split this problem into two subproblems.  */
  280.       compareseq (xoff, b, yoff, b - d);
  281.       /* This used to use f instead of b,
  282.          but that is incorrect!
  283.          It is not necessarily the case that diagonal d
  284.          has a snake from b to f.  */
  285.       compareseq (b, xlim, b - d, ylim);
  286.     }
  287.     }
  288. }
  289.  
  290. /* Discard lines from one file that have no matches in the other file.
  291.  
  292.    A line which is discarded will not be considered by the actual
  293.    comparison algorithm; it will be as if that line were not in the file.
  294.    The file's `realindexes' table maps virtual line numbers
  295.    (which don't count the discarded lines) into real line numbers;
  296.    this is how the actual comparison algorithm produces results
  297.    that are comprehensible when the discarded lines are counted.
  298.  
  299.    When we discard a line, we also mark it as a deletion or insertion
  300.    so that it will be printed in the output.  */
  301.  
  302. void discard_confusing_lines (struct file_data *filevec)
  303. {
  304.   unsigned int f, i;
  305.   char *discarded[2];
  306.   int *equiv_count[2];
  307.  
  308.   /* Allocate our results.  */
  309.   for (f = 0; f < 2; f++)
  310.     {
  311.       filevec[f].undiscarded
  312.     = (int *) xmalloc (filevec[f].buffered_lines * sizeof (int));
  313.       filevec[f].realindexes
  314.     = (int *) xmalloc (filevec[f].buffered_lines * sizeof (int));
  315.     }
  316.  
  317.   /* Set up equiv_count[F][I] as the number of lines in file F
  318.      that fall in equivalence class I.  */
  319.  
  320.   equiv_count[0] = (int *) xmalloc (filevec[0].equiv_max * sizeof (int));
  321.   bzero (equiv_count[0], filevec[0].equiv_max * sizeof (int));
  322.   equiv_count[1] = (int *) xmalloc (filevec[1].equiv_max * sizeof (int));
  323.   bzero (equiv_count[1], filevec[1].equiv_max * sizeof (int));
  324.  
  325.   for (i = 0; i < filevec[0].buffered_lines; ++i)
  326.     ++equiv_count[0][filevec[0].equivs[i]];
  327.   for (i = 0; i < filevec[1].buffered_lines; ++i)
  328.     ++equiv_count[1][filevec[1].equivs[i]];
  329.  
  330.   /* Set up tables of which lines are going to be discarded.  */
  331.  
  332.   discarded[0] = (char *) xmalloc (filevec[0].buffered_lines);
  333.   discarded[1] = (char *) xmalloc (filevec[1].buffered_lines);
  334.   bzero (discarded[0], filevec[0].buffered_lines);
  335.   bzero (discarded[1], filevec[1].buffered_lines);
  336.  
  337.   /* Mark to be discarded each line that matches no line of the other file.
  338.      If a line matches many lines, mark it as provisionally discardable.  */
  339.  
  340.   for (f = 0; f < 2; f++)
  341.     {
  342.       unsigned int end = filevec[f].buffered_lines;
  343.       char *discards = discarded[f];
  344.       int *counts = equiv_count[1 - f];
  345.       int *equivs = filevec[f].equivs;
  346.       unsigned int many = 5;
  347.       unsigned int tem = end / 64;
  348.  
  349.       /* Multiply MANY by approximate square root of number of lines.
  350.      That is the threshold for provisionally discardable lines.  */
  351.       while ((tem = tem >> 2) > 0)
  352.     many *= 2;
  353.  
  354.       for (i = 0; i < end; i++)
  355.     {
  356.       int nmatch;
  357.       if (equivs[i] == 0)
  358.         continue;
  359.       nmatch = counts[equivs[i]];
  360.       if (nmatch == 0)
  361.         discards[i] = 1;
  362.       else if (nmatch > many)
  363.         discards[i] = 2;
  364.     }
  365.     }
  366.  
  367.   /* Don't really discard the provisional lines except when they occur
  368.      in a run of discardables, with nonprovisionals at the beginning
  369.      and end.  */
  370.  
  371.   for (f = 0; f < 2; f++)
  372.     {
  373.       unsigned int end = filevec[f].buffered_lines;
  374.       register char *discards = discarded[f];
  375.  
  376.       for (i = 0; i < end; i++)
  377.     {
  378.       /* Cancel provisional discards not in middle of run of discards.  */
  379.       if (discards[i] == 2)
  380.         discards[i] = 0;
  381.       else if (discards[i] != 0)
  382.         {
  383.           /* We have found a nonprovisional discard.  */
  384.           register int j;
  385.           unsigned int length;
  386.           unsigned int provisional = 0;
  387.  
  388.           /* Find end of this run of discardable lines.
  389.          Count how many are provisionally discardable.  */
  390.           for (j = i; j < end; j++)
  391.         {
  392.           if (discards[j] == 0)
  393.             break;
  394.           if (discards[j] == 2)
  395.             ++provisional;
  396.         }
  397.  
  398.           /* Cancel provisional discards at end, and shrink the run.  */
  399.           while (j > i && discards[j - 1] == 2)
  400.         discards[--j] = 0, --provisional;
  401.  
  402.           /* Now we have the length of a run of discardable lines
  403.          whose first and last are not provisional.  */
  404.           length = j - i;
  405.  
  406.           /* If 1/4 of the lines in the run are provisional,
  407.          cancel discarding of all provisional lines in the run.  */
  408.           if (provisional * 4 > length)
  409.         {
  410.           while (j > i)
  411.             if (discards[--j] == 2)
  412.               discards[j] = 0;
  413.         }
  414.           else
  415.         {
  416.           register unsigned int consec;
  417.           unsigned int minimum = 1;
  418.           unsigned int tem = length / 4;
  419.  
  420.           /* MINIMUM is approximate square root of LENGTH/4.
  421.              A subrun of two or more provisionals can stand
  422.              when LENGTH is at least 16.
  423.              A subrun of 4 or more can stand when LENGTH >= 64.  */
  424.           while ((tem = tem >> 2) > 0)
  425.             minimum *= 2;
  426.           minimum++;
  427.  
  428.           /* Cancel any subrun of MINIMUM or more provisionals
  429.              within the larger run.  */
  430.           for (j = 0, consec = 0; j < length; j++)
  431.             if (discards[i + j] != 2)
  432.               consec = 0;
  433.             else if (minimum == ++consec)
  434.               /* Back up to start of subrun, to cancel it all.  */
  435.               j -= consec;
  436.             else if (minimum < consec)
  437.               discards[i + j] = 0;
  438.  
  439.           /* Scan from beginning of run
  440.              until we find 3 or more nonprovisionals in a row
  441.              or until the first nonprovisional at least 8 lines in.
  442.              Until that point, cancel any provisionals.  */
  443.           for (j = 0, consec = 0; j < length; j++)
  444.             {
  445.               if (j >= 8 && discards[i + j] == 1)
  446.             break;
  447.               if (discards[i + j] == 2)
  448.             consec = 0, discards[i + j] = 0;
  449.               else if (discards[i + j] == 0)
  450.             consec = 0;
  451.               else
  452.             consec++;
  453.               if (consec == 3)
  454.             break;
  455.             }
  456.  
  457.           /* I advances to the last line of the run.  */
  458.           i += length - 1;
  459.  
  460.           /* Same thing, from end.  */
  461.           for (j = 0, consec = 0; j < length; j++)
  462.             {
  463.               if (j >= 8 && discards[i - j] == 1)
  464.             break;
  465.               if (discards[i - j] == 2)
  466.             consec = 0, discards[i - j] = 0;
  467.               else if (discards[i - j] == 0)
  468.             consec = 0;
  469.               else
  470.             consec++;
  471.               if (consec == 3)
  472.             break;
  473.             }
  474.         }
  475.         }
  476.     }
  477.     }
  478.  
  479.   /* Actually discard the lines. */
  480.   for (f = 0; f < 2; f++)
  481.     {
  482.       char *discards = discarded[f];
  483.       unsigned int end = filevec[f].buffered_lines;
  484.       unsigned int j = 0;
  485.       for (i = 0; i < end; ++i)
  486.     if (no_discards || discards[i] == 0)
  487.       {
  488.         filevec[f].undiscarded[j] = filevec[f].equivs[i];
  489.         filevec[f].realindexes[j++] = i;
  490.       }
  491.     else
  492.       filevec[f].changed_flag[i] = 1;
  493.       filevec[f].nondiscarded_lines = j;
  494.     }
  495.  
  496.   free (discarded[1]);
  497.   free (discarded[0]);
  498.   free (equiv_count[1]);
  499.   free (equiv_count[0]);
  500. }
  501.  
  502. /* Adjust inserts/deletes of blank lines to join changes
  503.    as much as possible.
  504.  
  505.    We do something when a run of changed lines include a blank
  506.    line at one end and have an excluded blank line at the other.
  507.    We are free to choose which blank line is included.
  508.    `compareseq' always chooses the one at the beginning,
  509.    but usually it is cleaner to consider the following blank line
  510.    to be the "change".  The only exception is if the preceding blank line
  511.    would join this change to other changes.  */
  512.  
  513. int inhibit;
  514.  
  515. static void shift_boundaries (struct file_data *filevec)
  516. {
  517.   int f;
  518.  
  519.   if (inhibit)
  520.     return;
  521.  
  522.   for (f = 0; f < 2; f++)
  523.     {
  524.       char *changed = filevec[f].changed_flag;
  525.       char *other_changed = filevec[1-f].changed_flag;
  526.       int i = 0;
  527.       int j = 0;
  528.       int i_end = filevec[f].buffered_lines;
  529.       int preceding = -1;
  530.       int other_preceding = -1;
  531.  
  532.       while (1)
  533.     {
  534.       int start, end, other_start;
  535.  
  536.       /* Scan forwards to find beginning of another run of changes.
  537.          Also keep track of the corresponding point in the other file.  */
  538.  
  539.       while (i < i_end && changed[i] == 0)
  540.         {
  541.           while (other_changed[j++])
  542.         /* Non-corresponding lines in the other file
  543.            will count as the preceding batch of changes.  */
  544.         other_preceding = j;
  545.           i++;
  546.         }
  547.  
  548.       if (i == i_end)
  549.         break;
  550.  
  551.       start = i;
  552.       other_start = j;
  553.  
  554.       while (1)
  555.         {
  556.           /* Now find the end of this run of changes.  */
  557.  
  558.           while (i < i_end && changed[i] != 0) i++;
  559.           end = i;
  560.  
  561.           /* If the first changed line matches the following unchanged one,
  562.          and this run does not follow right after a previous run,
  563.          and there are no lines deleted from the other file here,
  564.          then classify the first changed line as unchanged
  565.          and the following line as changed in its place.  */
  566.  
  567.           /* You might ask, how could this run follow right after another?
  568.          Only because the previous run was shifted here.  */
  569.  
  570.           if (end != i_end
  571.           && files[f].equivs[start] == files[f].equivs[end]
  572.           && !other_changed[j]
  573.           && end != i_end
  574.           && !((preceding >= 0 && start == preceding)
  575.                || (other_preceding >= 0
  576.                && other_start == other_preceding)))
  577.         {
  578.           changed[end++] = 1;
  579.           changed[start++] = 0;
  580.           ++i;
  581.           /* Since one line-that-matches is now before this run
  582.              instead of after, we must advance in the other file
  583.              to keep in synch.  */
  584.           ++j;
  585.         }
  586.           else
  587.         break;
  588.         }
  589.  
  590.       preceding = i;
  591.       other_preceding = j;
  592.     }
  593.     }
  594. }
  595.  
  596. /* Cons an additional entry onto the front of an edit script OLD.
  597.    LINE0 and LINE1 are the first affected lines in the two files (origin 0).
  598.    DELETED is the number of lines deleted here from file 0.
  599.    INSERTED is the number of lines inserted here in file 1.
  600.  
  601.    If DELETED is 0 then LINE0 is the number of the line before
  602.    which the insertion was done; vice versa for INSERTED and LINE1.  */
  603.  
  604. static struct change *add_change (int line0, int line1, int deleted, int inserted, struct change *old)
  605. {
  606.   struct change *new = (struct change *) xmalloc (sizeof (struct change));
  607.  
  608.   new->line0 = line0;
  609.   new->line1 = line1;
  610.   new->inserted = inserted;
  611.   new->deleted = deleted;
  612.   new->link = old;
  613.   return new;
  614. }
  615.  
  616. /* Scan the tables of which lines are inserted and deleted,
  617.    producing an edit script in reverse order.  */
  618.  
  619. static struct change *build_reverse_script (struct file_data *filevec)
  620. {
  621.   struct change *script = 0;
  622.   char *changed0 = filevec[0].changed_flag;
  623.   char *changed1 = filevec[1].changed_flag;
  624.   int len0 = filevec[0].buffered_lines;
  625.   int len1 = filevec[1].buffered_lines;
  626.  
  627.   /* Note that changedN[len0] does exist, and contains 0.  */
  628.  
  629.   int i0 = 0, i1 = 0;
  630.  
  631.   while (i0 < len0 || i1 < len1)
  632.     {
  633.       if (changed0[i0] || changed1[i1])
  634.     {
  635.       int line0 = i0, line1 = i1;
  636.  
  637.       /* Find # lines changed here in each file.  */
  638.       while (changed0[i0]) ++i0;
  639.       while (changed1[i1]) ++i1;
  640.  
  641.       /* Record this change.  */
  642.       script = add_change (line0, line1, i0 - line0, i1 - line1, script);
  643.     }
  644.  
  645.       /* We have reached lines in the two files that match each other.  */
  646.       i0++, i1++;
  647.     }
  648.  
  649.   return script;
  650. }
  651.  
  652. /* Scan the tables of which lines are inserted and deleted,
  653.    producing an edit script in forward order.  */
  654.  
  655. static struct change *build_script (struct file_data *filevec)
  656. {
  657.   struct change *script = 0;
  658.   char *changed0 = filevec[0].changed_flag;
  659.   char *changed1 = filevec[1].changed_flag;
  660.   int len0 = filevec[0].buffered_lines;
  661.   int len1 = filevec[1].buffered_lines;
  662.   int i0 = len0, i1 = len1;
  663.  
  664.   /* Note that changedN[-1] does exist, and contains 0.  */
  665.  
  666. #if 0 /* Unnecessary since a line includes its trailing newline.  */
  667.   /* In RCS comparisons, making the existence or nonexistence of trailing
  668.      newlines really matter. */
  669.   if (output_style == OUTPUT_RCS
  670.       && filevec[0].missing_newline != filevec[1].missing_newline)
  671.     changed0[len0 - 1] = changed1[len1 - 1] = 1;
  672. #endif
  673.  
  674.   while (i0 >= 0 || i1 >= 0)
  675.     {
  676.       if (changed0[i0 - 1] || changed1[i1 - 1])
  677.     {
  678.       int line0 = i0, line1 = i1;
  679.  
  680.       /* Find # lines changed here in each file.  */
  681.       while (changed0[i0 - 1]) --i0;
  682.       while (changed1[i1 - 1]) --i1;
  683.  
  684.       /* Record this change.  */
  685.       script = add_change (i0, i1, line0 - i0, line1 - i1, script);
  686.     }
  687.  
  688.       /* We have reached lines in the two files that match each other.  */
  689.       i0--, i1--;
  690.     }
  691.  
  692.   return script;
  693. }
  694.  
  695. /* Report the differences of two files.  DEPTH is the current directory
  696.    depth. */
  697. int diff_2_files (struct file_data *filevec, int depth)
  698. {
  699.   int diags;
  700.   int i;
  701.   struct change *e, *p;
  702.   struct change *script;
  703.   int binary;
  704.   int changes;
  705.  
  706.   binary = read_files (filevec);
  707.  
  708.   /* If we have detected that file 0 is a binary file,
  709.      compare the two files as binary.  This can happen
  710.      only when the first chunk is read.
  711.      Also, -q means treat all files as binary.  */
  712.  
  713.   if (binary || no_details_flag)
  714.     {
  715.       int differs = (filevec[0].buffered_chars != filevec[1].buffered_chars
  716.              || bcmp (filevec[0].buffer, filevec[1].buffer,
  717.                   filevec[1].buffered_chars));
  718.       if (differs) 
  719.     message (binary ? "Binary files %s and %s differ\n"
  720.          : "Files %s and %s differ\n",
  721.          filevec[0].name, filevec[1].name);
  722.  
  723.       for (i = 0; i < 2; ++i)
  724.     if (filevec[i].buffer)
  725.       free (filevec[i].buffer);
  726.       return differs;
  727.     }
  728.  
  729.   /* Allocate vectors for the results of comparison:
  730.      a flag for each line of each file, saying whether that line
  731.      is an insertion or deletion.
  732.      Allocate an extra element, always zero, at each end of each vector.  */
  733.  
  734.   filevec[0].changed_flag = (char *) xmalloc (filevec[0].buffered_lines + 2);
  735.   filevec[1].changed_flag = (char *) xmalloc (filevec[1].buffered_lines + 2);
  736.   bzero (filevec[0].changed_flag, filevec[0].buffered_lines + 2);
  737.   bzero (filevec[1].changed_flag, filevec[1].buffered_lines + 2);
  738.   filevec[0].changed_flag++;
  739.   filevec[1].changed_flag++;
  740.  
  741.   /* Some lines are obviously insertions or deletions
  742.      because they don't match anything.  Detect them now,
  743.      and avoid even thinking about them in the main comparison algorithm.  */
  744.  
  745.   discard_confusing_lines (filevec);
  746.  
  747.   /* Now do the main comparison algorithm, considering just the
  748.      undiscarded lines.  */
  749.  
  750.   xvec = filevec[0].undiscarded;
  751.   yvec = filevec[1].undiscarded;
  752.   diags = filevec[0].nondiscarded_lines + filevec[1].nondiscarded_lines + 3;
  753.   fdiag = (int *) xmalloc (diags * sizeof (int));
  754.   fdiag += filevec[1].nondiscarded_lines + 1;
  755.   bdiag = (int *) xmalloc (diags * sizeof (int));
  756.   bdiag += filevec[1].nondiscarded_lines + 1;
  757.  
  758.   files[0] = filevec[0];
  759.   files[1] = filevec[1];
  760.  
  761.   compareseq (0, filevec[0].nondiscarded_lines,
  762.           0, filevec[1].nondiscarded_lines);
  763.  
  764.   bdiag -= filevec[1].nondiscarded_lines + 1;
  765.   free (bdiag);
  766.   fdiag -= filevec[1].nondiscarded_lines + 1;
  767.   free (fdiag);
  768.  
  769.   /* Modify the results slightly to make them prettier
  770.      in cases where that can validly be done.  */
  771.  
  772.   shift_boundaries (filevec);
  773.  
  774.   /* Get the results of comparison in the form of a chain
  775.      of `struct change's -- an edit script.  */
  776.  
  777.   if (output_style == OUTPUT_ED)
  778.     script = build_reverse_script (filevec);
  779.   else
  780.     script = build_script (filevec);
  781.  
  782.   if (script || output_style == OUTPUT_IFDEF)
  783.     {
  784.       setup_output (files[0].name, files[1].name, depth);
  785.  
  786.       switch (output_style)
  787.     {
  788.     case OUTPUT_CONTEXT:
  789.       print_context_header (files, 0);
  790.       print_context_script (script, 0);
  791.       break;
  792.  
  793.     case OUTPUT_UNIFIED:
  794.       print_context_header (files, 1);
  795.       print_context_script (script, 1);
  796.       break;
  797.  
  798.     case OUTPUT_ED:
  799.       print_ed_script (script);
  800.       break;
  801.  
  802.     case OUTPUT_FORWARD_ED:
  803.       pr_forward_ed_script (script);
  804.       break;
  805.  
  806.     case OUTPUT_RCS:
  807.       print_rcs_script (script);
  808.       break;
  809.  
  810.     case OUTPUT_NORMAL:
  811.       print_normal_script (script);
  812.       break;
  813.  
  814.     case OUTPUT_IFDEF:
  815.       print_ifdef_script (script);
  816.       break;
  817.     }
  818.  
  819.       finish_output ();
  820.     }
  821.  
  822.   /* Set CHANGES if we had any diffs that were printed.
  823.      If some changes are being ignored, we must scan the script to decide.  */
  824.   if (ignore_blank_lines_flag || ignore_regexp)
  825.     {
  826.       struct change *next = script;
  827.       changes = 0;
  828.  
  829.       while (next && changes == 0)
  830.     {
  831.       struct change *this, *end;
  832.       int first0, last0, first1, last1, deletes, inserts;
  833.  
  834.       /* Find a set of changes that belong together.  */
  835.       this = next;
  836.       end = find_change (next);
  837.  
  838.       /* Disconnect them from the rest of the changes,
  839.          making them a hunk, and remember the rest for next iteration.  */
  840.       next = end->link;
  841.       end->link = NULL;
  842.  
  843.       /* Determine whether this hunk was printed.  */
  844.       analyze_hunk (this, &first0, &last0, &first1, &last1,
  845.             &deletes, &inserts);
  846.  
  847.       /* Reconnect the script so it will all be freed properly.  */
  848.       end->link = next;
  849.  
  850.       if (deletes || inserts)
  851.         changes = 1;
  852.     }
  853.     }
  854.   else
  855.     changes = (script != 0);
  856.  
  857.   for (i = 1; i >= 0; --i)
  858.     {
  859.       free (filevec[i].realindexes);
  860.       free (filevec[i].undiscarded);
  861.     }
  862.  
  863.   for (i = 1; i >= 0; --i)
  864.     free (--filevec[i].changed_flag);
  865.  
  866.   for (i = 1; i >= 0; --i)
  867.     free (filevec[i].equivs);
  868.  
  869.   for (i = 0; i < 2; ++i)
  870.     {
  871.       if (filevec[i].buffer != 0)
  872.     free (filevec[i].buffer);
  873.       free (filevec[i].linbuf);
  874.     }
  875.  
  876.   for (e = script; e; e = p)
  877.     {
  878.       p = e->link;
  879.       free (e);
  880.     }
  881.  
  882.   if (! ROBUST_OUTPUT_STYLE (output_style)
  883.       /* For -D, invent newlines silently.  That's ok in C code.  */
  884.       && output_style != OUTPUT_IFDEF)
  885.     for (i = 0; i < 2; ++i)
  886.       if (filevec[i].missing_newline)
  887.     {
  888.       error ("No newline at end of file %s", filevec[i].name, "");
  889.       changes = 2;
  890.     }
  891.  
  892.   return changes;
  893. }
  894.